package com.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.customer.dao.ClientMapper;
import com.customer.dao.IntegrationHistoryMapper;
import com.customer.dao.MemberLevelMapper;
import com.customer.fegin.WeiXinPayFegin;
import com.customer.service.IntegrationHistoryService;
import com.nameless.entity.Client;
import com.nameless.entity.IntegrationHistory;
import com.nameless.entity.MemberLevel;
import com.nameless.util.JwtUtil;
import com.nameless.util.WebUtils;
import com.nameless.vo.IntegrationHistoryVo;
import com.nameless.vo.Result;
import com.nameless.vo.pay.RequestParams;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * -*- coding:utf-8 -*-
 *
 * @author 太阳偷渡青山
 * @software IntelliJ IDEA
 * @date 2023/03/04 15:10
 * @Description
 */
@Service
@Slf4j
public class IntegrationHistoryServiceImpl extends ServiceImpl<IntegrationHistoryMapper,IntegrationHistory> implements IntegrationHistoryService {

    @Autowired
    private ClientMapper clientMapper;

    @Override
    public Client getInitialHistory() {
        return getTokenClient();
    }

    @Autowired
    private WeiXinPayFegin payFegin;

    @Override
    @Transactional
    public Result<Map<String, Object>> createKryptonGold(String amount,Integer status) {
        RequestParams requestParams = new RequestParams();
        long clientId = getTokenClient().getId().longValue();
        requestParams.setClientId(clientId);
        requestParams.setMoney(new BigDecimal(amount));
        requestParams.setDescribe("为钱包充值平驾币,充值送积分");
        requestParams.setReturnUrl("http://localhost:8080/#/wallet");
        Result<Map<String, Object>> aNative =  null;
        if (status == 1){
            aNative = payFegin.createNative(requestParams);
        }else if(status == 2){
            aNative = payFegin.createAliPay(requestParams);
        }
        if (aNative != null && aNative.getCode() == 200) {
            String orderNo = (String) aNative.getData().get("orderNo");
            createIntegrationHistory(orderNo,clientId,amount,status);
        }
        return aNative;
    }

    @Override
    public Result<Map<String, Object>> payNative(String orderNo,Integer status) {
        IntegrationHistory history = getByOrderNo(orderNo);
        if (history.getIsPay() == 1){
            return Result.error("该订单已支付，，请勿重复支付！！！");
        }else {
            RequestParams requestParams = new RequestParams();
            requestParams.setOrderNo(history.getOrderNo());
            requestParams.setMoney(history.getAmount());
            requestParams.setDescribe(history.getOperateNote());
            requestParams.setReturnUrl("http://localhost:8080/#/wallet");
            if (status == 1 ){
                return payFegin.payExistingOrder(requestParams);
            }else if(status == 2) {
                return payFegin.createAliPay(requestParams);
            }
        }
        return null;
    }

    @Override
    public String payCar(IntegrationHistoryVo historyVo) {
        long clientId = getTokenClient().getId().longValue();
        IntegrationHistory history = new IntegrationHistory();
        history.setOrderNo(historyVo.getOrderNo());
        history.setCreateTime(new Date());
        history.setMemberId(clientId);
        history.setAmount(new BigDecimal(historyVo.getAmount()));
        history.setAmountType(2);
        history.setChangeCount(historyVo.getCount());
        history.setChangeType(1);
        history.setStatus(historyVo.getStatus());
        history.setOperateNote(historyVo.getOperateNote());
        history.setIsPay(0);
        int insert = baseMapper.insert(history);
        return insert>0 ? "添加明细成功":"添加明细失败";
    }

    @Override
    @Transactional
    public boolean payCarSuccess(String orderNo) {
        IntegrationHistory history = getByOrderNo(orderNo);
        history.setIsPay(1);
        int updateById = baseMapper.updateById(history);
        int insertGrowth = insertGrowth(2,history.getAmount(), history.getChangeCount());
        return updateById > 0 && insertGrowth > 0;
    }

    @Override
    public Result<String> cancelPayment(String orderNo) {
        IntegrationHistory history = getByOrderNo(orderNo);
        history.setIsPay(2);
        int i = baseMapper.updateById(history);
        return 1 > 0 ?Result.success("取消订单成功"):Result.error("取消订单失败");
    }

    @Autowired
    private MemberLevelMapper memberLevelMapper;

    @Override
    @Transactional
    public Result queryPayStatus(String orderNo,Integer status) {
        Result stringResult = null;
        if (status == 1) {
            stringResult = payFegin.queryPayStatus(orderNo);
        }else if(status == 2) {
            stringResult = payFegin.payReturn(orderNo);
        }
        log.info("============{}",stringResult);
        if (stringResult.getCode() == 200){
            IntegrationHistory history = getByOrderNo(orderNo);
            history.setIsPay(1);
            int updateById = baseMapper.updateById(history);
            int insertGrowth = insertGrowth(1,history.getAmount(), history.getChangeCount());
            return updateById> 0 && insertGrowth > 0 ? stringResult:Result.error("修改账号余额失败");
        }
        return stringResult;
    }

    /**
     * 获取订单列表
     *
     * @return {@link List}<{@link IntegrationHistory}>
     */
    @Override
    public List<IntegrationHistory> getListByClientId() {
        Integer clientId = getTokenClient().getId();
        LambdaQueryWrapper<IntegrationHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IntegrationHistory::getMemberId,clientId);
        queryWrapper.orderByDesc(IntegrationHistory::getCreateTime);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 创建积分历史，支付状态为未支付
     *
     * @param orderNo  订单没有
     * @param clientId 客户机id
     * @param amount   量
     */
    public void createIntegrationHistory(String orderNo,Long clientId,String amount,Integer status){
        IntegrationHistory history = new IntegrationHistory();
        history.setMemberId(clientId);
        history.setOrderNo(orderNo);
        history.setCreateTime(new Date());
        history.setAmount(new BigDecimal(amount));
        history.setAmountType(1);
        history.setChangeType(1);
        history.setStatus(status);
        Integer count = Integer.parseInt(amount)/10;
        history.setChangeCount(count);
        history.setOperateNote("为钱包充值平驾币,充值送积分");
        history.setIsPay(0);
        baseMapper.insert(history);
    }

    /**
     * 获得令牌客户
     *
     * @return {@link Client}
     */
    private Client getTokenClient(){
        // 获取token值,获取用户id
        String token = WebUtils.getRequest().getHeader("token");
        Map<String, Object> tokenChaim = JwtUtil.getTokenChaim(token);
        String username = (String) tokenChaim.get("clientname");
        LambdaQueryWrapper<Client> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Client::getUsername,username);
        return clientMapper.selectOne(queryWrapper);
    }


    /**
     * 得到订单历史
     *
     * @param orderNo 订单没有
     * @return {@link IntegrationHistory}
     */
    private IntegrationHistory getByOrderNo(String orderNo){
        LambdaUpdateWrapper<IntegrationHistory> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(IntegrationHistory::getOrderNo,orderNo);
        return baseMapper.selectOne(wrapper);
    }

    /**
     * 添加账号的余额、积分，增加成长值
     *
     * 租车杰少账号的余额，增加成长值
     *
     * 提升成长值为积分的十分之一
     *
     * @param amount      余额
     * @param integration 集成
     */
    private int insertGrowth(Integer type,BigDecimal amount,Integer integration ){
        // 修改账号的积分与余额
        Client client = getTokenClient();
        if (type == 1){
            client.setAccountBalance(client.getAccountBalance().add(amount));
            client.setIntegration(client.getIntegration() + integration);
            client.setHistoryIntegration(client.getHistoryIntegration() + integration);
        }else if (type == 2){
            client.setAccountBalance(client.getAccountBalance().subtract(amount));
        }
        client.setGrowth(client.getGrowth() + integration * 0.01);

        // 判断该提升成长值后是否满足提升等级
        MemberLevel memberLevel = memberLevelMapper.selectById(client.getMemberLevelId());
        if (client.getGrowth() > memberLevel.getGrowthPoint() && client.getMemberLevelId() != 5){
            client.setMemberLevelId(client.getMemberLevelId() + 1);
        }
        return clientMapper.updateById(client);
    }


}
